package com.qd.panda.service.func;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.exception.ApiException;
import com.qd.common.panda.domain.entity.func.ChannelEnableDTO;
import com.qd.common.panda.domain.entity.func.ChannelFunDTO;
import com.qd.panda.model.ChannelFun;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sjk
 */
@Service
@RequiredArgsConstructor
public class ChannelOptionService {

    private final ChannelService channelService;
    private final ChannelFunService channelFunService;
    private final ChannelUserService channelUserService;

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<String> ids) {
        if (ids.size() == 1) {
            channelService.removeById(ids.get(0));
            channelFunService.removeByChannelCode(ids.get(0));
            if(channelUserService.isExistsByChannelCode(ids.get(0))){
                throw new ApiException("不能删除");
            }
        } else {
            channelService.removeBatchIds(ids);
            for (String channelCode : ids) {
                if(channelUserService.isExistsByChannelCode(channelCode)){
                    throw new ApiException("不能删除");
                }
                channelFunService.removeByChannelCode(channelCode);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void enable(ChannelEnableDTO dto) {
        channelService.enable(dto);

        List<String> idList = new ArrayList<>();
        for (String channelCode : dto.getIds()) {
            List<ChannelFun> list = getChannelFunList(dto, channelCode);
            if (!list.isEmpty()) {
                idList.addAll(list.stream().map(ChannelFun::getFuncId).collect(Collectors.toList()));
            }
        }
        if (!idList.isEmpty()) {
            ChannelEnableDTO child = new ChannelEnableDTO();
            child.setEnable(dto.getEnable());
            child.setIds(idList);
            channelFunService.enable(child);
            child.freeData();
        }
    }

    private List<ChannelFun> getChannelFunList(ChannelEnableDTO dto, String channelCode) {
        ChannelFunDTO query = new ChannelFunDTO();
        query.setEnable(dto.getEnable().equals(ConstantDto.SF1) ? ConstantDto.SF0 : ConstantDto.SF1);
        query.setChannelCode(channelCode);
        List<ChannelFun> list = channelFunService.getList(query);
        query.freeData();
        return list;
    }
}
